import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import '../constants/app_colors.dart';
import '../services/ble_service.dart';
import '../utils/permission_helper.dart';

class SettingsScreen extends StatefulWidget {
  const SettingsScreen({Key? key}) : super(key: key);

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  final BleService _bleService = BleService();
  bool _isScanning = false;
  bool _blueToothEnabled = false;
  bool _autoConnect = true;
  StreamSubscription? _scanSubscription;
  StreamSubscription? _stateSubscription;
  StreamSubscription? _connectionChangeSubscription;
  Timer? _connectionCheckTimer;
  final List<BluetoothDevice> _scanResults = [];

  @override
  void initState() {
    super.initState();
    _initBluetooth();
    _autoConnect = _bleService.isAutoConnectEnabled;
  }

  Future<void> _initBluetooth() async {
    // 初始化蓝牙服务
    await _bleService.initialize();

    // 监听蓝牙状态
    _stateSubscription = _bleService.bluetoothStateStream.listen((state) {
      if (mounted) {
        setState(() {
          _blueToothEnabled = state == BluetoothAdapterState.on;

          // 如果蓝牙关闭，停止扫描并清空列表
          if (!_blueToothEnabled && _isScanning) {
            _stopScan();
            _scanResults.clear();
          }
        });
      }
    });

    // 监听连接状态变化
    _connectionChangeSubscription = _bleService.connectionChangeStream.listen((_) {
      if (mounted) {
        setState(() {
          // 刷新UI显示
          _loadConnectedDevices();
        });
      }
    });

    // 加载已连接的设备
    _loadConnectedDevices();

    // 定期检查连接状态
    _connectionCheckTimer = Timer.periodic(const Duration(seconds: 5), (timer) {
      if (mounted) {
        _bleService.checkDevicesConnectionStatus();
      } else {
        timer.cancel();
      }
    });
  }

  Future<void> _loadConnectedDevices() async {
    try {
      // 使用BleService管理的设备
      final connectedDevices = _bleService.allConnectedDevices.map((cd) => cd.device).toList();

      if (mounted) {
        setState(() {
          // 更新扫描结果中的设备状态
          for (var device in _scanResults) {
            final isConnected = connectedDevices.any((d) => d.remoteId.str == device.remoteId.str);
            if (isConnected && !connectedDevices.contains(device)) {
              // 如果设备已连接但不在扫描结果中，添加它
              _scanResults.add(device);
            }
          }
        });
      }
    } catch (e) {
      debugPrint('加载已连接设备错误: $e');
    }
  }

  Future<void> _startScan() async {
    // 先请求权限
    final hasPermission = await PermissionHelper.requestBluetoothPermissions(context);
    if (!hasPermission) {
      return;
    }

    if (mounted) {
      setState(() {
        _isScanning = true;
      });
    }

    try {
      // 开始扫描
      await _bleService.startScan();

      // 监听扫描结果
      _scanSubscription = _bleService.scanResultsStream.listen((device) {
        // 添加设备到列表（如果不存在）
        final bool deviceExists = _scanResults.any((d) => d.remoteId.str == device.remoteId.str);
        if (!deviceExists && mounted) {
          setState(() {
            _scanResults.add(device);
          });
        }
      });

      // 10秒后自动停止扫描
      Future.delayed(const Duration(seconds: 10), () {
        if (mounted && _isScanning) {
          _stopScan();
        }
      });
    } catch (e) {
      debugPrint('开始扫描错误: $e');
      _stopScan();
    }
  }

  Future<void> _stopScan() async {
    if (!_isScanning) return;

    try {
      await _bleService.stopScan();

      if (_scanSubscription != null) {
        await _scanSubscription!.cancel();
        _scanSubscription = null;
      }
    } catch (e) {
      debugPrint('停止扫描错误: $e');
    } finally {
      if (mounted) {
        setState(() {
          _isScanning = false;
        });
      }
    }
  }

  Future<void> _connectToDevice(BluetoothDevice device) async {
    try {
      // 先停止扫描
      await _stopScan();

      // 显示连接中
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('正在连接到: ${device.platformName}')),
        );
      }

      // 连接设备
      final bool success = await _bleService.connectToDevice(device);

      if (success && mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已连接到: ${device.platformName}')),
        );
      } else if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('连接失败: 未找到所需的服务或特征')),
        );
      }
    } catch (e) {
      debugPrint('连接设备错误: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('连接错误: $e')),
        );
      }
    }
  }

  Future<void> _disconnectDevice(BluetoothDevice device) async {
    try {
      await _bleService.disconnectDevice(device);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已断开设备: ${device.platformName}')),
        );
      }
    } catch (e) {
      debugPrint('断开连接错误: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('断开连接错误: $e')),
        );
      }
    }
  }

  @override
  void dispose() {
    // 取消Timer
    _connectionCheckTimer?.cancel();

    // 停止扫描
    _stopScan();

    // 取消所有订阅
    _stateSubscription?.cancel();
    _connectionChangeSubscription?.cancel();
    _scanSubscription?.cancel();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final allConnectedDevices = _bleService.allConnectedDevices;

    return Scaffold(
      backgroundColor: AppColors.background,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: const Text(
          '蓝牙设置',
          style: TextStyle(
            color: AppColors.textPrimary,
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
        ),
        leading: IconButton(
          icon: Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(12),
            ),
            child: const Icon(Icons.arrow_back, color: AppColors.textPrimary, size: 20),
          ),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 蓝牙状态卡片
            _buildStatusCard(),

            const SizedBox(height: 20),

            // 自动连接设置卡片
            if (_blueToothEnabled) _buildAutoConnectCard(),

            if (_blueToothEnabled) const SizedBox(height: 20),

            // 已连接设备区域
            _buildConnectedDevicesSection(allConnectedDevices),

            const SizedBox(height: 20),

            // 扫描按钮
            _buildScanButton(),

            const SizedBox(height: 20),

            // 可用设备区域
            _buildAvailableDevicesSection(),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusCard() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: _blueToothEnabled
            ? [AppColors.primary.withOpacity(0.1), AppColors.primary.withOpacity(0.05)]
            : [Colors.grey.withOpacity(0.1), Colors.grey.withOpacity(0.05)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: _blueToothEnabled ? AppColors.primary.withOpacity(0.3) : Colors.grey.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: _blueToothEnabled ? AppColors.primary : Colors.grey,
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(
              _blueToothEnabled ? Icons.bluetooth_connected : Icons.bluetooth_disabled,
              color: Colors.white,
              size: 28,
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '蓝牙状态',
                  style: TextStyle(
                    color: AppColors.textPrimary,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  _blueToothEnabled ? '蓝牙已开启，可以连接设备' : '蓝牙已关闭，请在系统设置中开启',
                  style: TextStyle(
                    color: _blueToothEnabled ? AppColors.success : Colors.red,
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
            decoration: BoxDecoration(
              color: _blueToothEnabled ? AppColors.success : Colors.red,
              borderRadius: BorderRadius.circular(20),
            ),
            child: Text(
              _blueToothEnabled ? '已开启' : '已关闭',
              style: const TextStyle(
                color: Colors.white,
                fontSize: 12,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAutoConnectCard() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: AppColors.cardBackground,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: _autoConnect ? AppColors.primary.withOpacity(0.1) : Colors.grey.withOpacity(0.1),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(
              Icons.autorenew,
              color: _autoConnect ? AppColors.primary : Colors.grey,
              size: 24,
            ),
          ),
          const SizedBox(width: 16),
          const Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '自动连接',
                  style: TextStyle(
                    color: AppColors.textPrimary,
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                SizedBox(height: 4),
                Text(
                  '自动连接已配对的设备',
                  style: TextStyle(
                    color: AppColors.textSecondary,
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          ),
          Switch(
            value: _autoConnect,
            onChanged: (value) {
              setState(() {
                _autoConnect = value;
                _bleService.isAutoConnectEnabled = value;
              });
            },
            activeColor: AppColors.primary,
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          ),
        ],
      ),
    );
  }

  Widget _buildConnectedDevicesSection(List<dynamic> allConnectedDevices) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            const Icon(Icons.devices_other, color: AppColors.primary, size: 20),
            const SizedBox(width: 8),
            Text(
              '已连接设备',
              style: const TextStyle(
                color: AppColors.textPrimary,
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(width: 8),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: AppColors.primary,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                '${allConnectedDevices.length}',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        if (allConnectedDevices.isEmpty)
          Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.grey.withOpacity(0.2)),
            ),
            child: const Center(
              child: Column(
                children: [
                  Icon(Icons.bluetooth_disabled, size: 32, color: Colors.grey),
                  SizedBox(height: 8),
                  Text(
                    '暂无已连接设备',
                    style: TextStyle(color: AppColors.textSecondary),
                  ),
                ],
              ),
            ),
          )
        else
          ...allConnectedDevices.map((device) => Container(
            margin: const EdgeInsets.only(bottom: 8),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: AppColors.success.withOpacity(0.3)),
              boxShadow: [
                BoxShadow(
                  color: AppColors.success.withOpacity(0.1),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    color: AppColors.success.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: const Icon(
                    Icons.bluetooth_connected,
                    color: AppColors.success,
                    size: 24,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        device.device.platformName,
                        style: const TextStyle(
                          color: AppColors.textPrimary,
                          fontWeight: FontWeight.w600,
                          fontSize: 16,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        '设备ID: ${device.device.remoteId.toString().substring(0, 8)}...',
                        style: const TextStyle(
                          color: AppColors.textSecondary,
                          fontSize: 12,
                        ),
                      ),
                      Container(
                        margin: const EdgeInsets.only(top: 4),
                        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                        decoration: BoxDecoration(
                          color: AppColors.success.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: Text(
                          '设备 ${allConnectedDevices.indexOf(device) + 1}',
                          style: const TextStyle(
                            color: AppColors.success,
                            fontSize: 10,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                TextButton.icon(
                  onPressed: () => _disconnectDevice(device.device),
                  icon: const Icon(Icons.link_off, size: 16),
                  label: const Text('断开'),
                  style: TextButton.styleFrom(
                    foregroundColor: Colors.red,
                    backgroundColor: Colors.red.withOpacity(0.1),
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                ),
              ],
            ),
          )).toList(),
      ],
    );
  }

  Widget _buildScanButton() {
    return Container(
      width: double.infinity,
      height: 56,
      decoration: BoxDecoration(
        gradient: _blueToothEnabled
          ? LinearGradient(
              colors: _isScanning
                ? [Colors.red, Colors.red.shade400]
                : [AppColors.primary, AppColors.primary.withOpacity(0.8)],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            )
          : null,
        color: !_blueToothEnabled ? Colors.grey.withOpacity(0.3) : null,
        borderRadius: BorderRadius.circular(16),
        boxShadow: _blueToothEnabled ? [
          BoxShadow(
            color: (_isScanning ? Colors.red : AppColors.primary).withOpacity(0.3),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ] : null,
      ),
      child: ElevatedButton.icon(
        onPressed: _blueToothEnabled ? (_isScanning ? _stopScan : _startScan) : null,
        icon: _isScanning
          ? const SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
              ),
            )
          : const Icon(Icons.search, size: 24),
        label: Text(
          _isScanning ? '正在扫描设备...' : '开始扫描设备',
          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
        ),
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.transparent,
          foregroundColor: Colors.white,
          shadowColor: Colors.transparent,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
        ),
      ),
    );
  }

  Widget _buildAvailableDevicesSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            const Icon(Icons.bluetooth_searching, color: AppColors.primary, size: 20),
            const SizedBox(width: 8),
            const Text(
              '可用设备',
              style: TextStyle(
                color: AppColors.textPrimary,
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            if (_autoConnect && !_isScanning) ...[
              const SizedBox(width: 8),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: AppColors.success.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: const Text(
                  '自动连接开启',
                  style: TextStyle(
                    color: AppColors.success,
                    fontSize: 10,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ],
        ),
        const SizedBox(height: 12),
        Container(
          height: 300,
          decoration: BoxDecoration(
            color: AppColors.cardBackground,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.grey.withOpacity(0.2)),
          ),
          child: _getDeviceListWidget(),
        ),
      ],
    );
  }

  Widget _getDeviceListWidget() {
    // 过滤出HQ STALK开头的设备
    final List<BluetoothDevice> filteredDevices = _scanResults
        .where((device) => device.platformName.startsWith('HQ STALK'))
        .toList();

    // 从结果中排除已连接的设备 - 使用remoteId.str进行比较
    final connectedDeviceIds = _bleService.allConnectedDevices
        .map((d) => d.device.remoteId.str)
        .toList();

    final availableDevices = filteredDevices
        .where((d) => !connectedDeviceIds.contains(d.remoteId.str))
        .toList();

    if (availableDevices.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              _blueToothEnabled ? Icons.bluetooth_searching : Icons.bluetooth_disabled,
              size: 48,
              color: Colors.grey.withValues(alpha: 0.6),
            ),
            const SizedBox(height: 16),
            Text(
              _blueToothEnabled
                ? (_isScanning ? '正在搜索设备...' : '未找到可用设备')
                : '请先开启蓝牙',
              style: const TextStyle(
                color: AppColors.textSecondary,
                fontSize: 16,
              ),
            ),
            if (_blueToothEnabled && !_isScanning) ...[
              const SizedBox(height: 8),
              const Text(
                '点击扫描按钮开始搜索',
                style: TextStyle(
                  color: AppColors.textSecondary,
                  fontSize: 12,
                ),
              ),
            ],
          ],
        ),
      );
    }

    return ListView.separated(
      padding: const EdgeInsets.all(12),
      itemCount: availableDevices.length,
      separatorBuilder: (context, index) => const SizedBox(height: 8),
      itemBuilder: (context, index) {
        final BluetoothDevice device = availableDevices[index];

        return Container(
          key: ValueKey(device.remoteId.str),
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: AppColors.primary.withValues(alpha: 0.2)),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.05),
                blurRadius: 8,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: AppColors.primary.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: const Icon(
                  Icons.bluetooth,
                  color: AppColors.primary,
                  size: 24,
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      device.platformName.isNotEmpty
                          ? device.platformName
                          : '未知设备',
                      style: const TextStyle(
                        color: AppColors.textPrimary,
                        fontWeight: FontWeight.w600,
                        fontSize: 16,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '设备ID: ${device.remoteId.toString().substring(0, 8)}...',
                      style: const TextStyle(
                        color: AppColors.textSecondary,
                        fontSize: 12,
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 4),
                      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(
                        color: AppColors.primary.withValues(alpha: 0.1),
                        borderRadius: BorderRadius.circular(6),
                      ),
                      child: const Text(
                        '可连接',
                        style: TextStyle(
                          color: AppColors.primary,
                          fontSize: 10,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 8),
              Container(
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    colors: [AppColors.primary, AppColors.primary],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  borderRadius: BorderRadius.circular(10),
                  boxShadow: [
                    BoxShadow(
                      color: AppColors.primary.withValues(alpha: 0.3),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: ElevatedButton.icon(
                  onPressed: () => _connectToDevice(device),
                  icon: const Icon(Icons.link, size: 16),
                  label: const Text('连接'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.transparent,
                    foregroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}